package vineetmanohar.timelock;

import java.util.Calendar;
import java.util.Date;

/**
 * An in memory implementation of TimeLock
 * 
 * @author Vineet Manohar
 */
public class InMemoryTimeLock implements TimeLock {
	private Date expiryDate;

	/**
	 * create a new lock which is open at creation time
	 */
	public InMemoryTimeLock() {
		this.expiryDate = new Date();
	}

	/**
	 * @return true if the time lock is past its expiry date
	 */
	public boolean isLocked() {
		return expiryDate.after(new Date());
	}

	public void lock(int milliseconds) {
		this.expiryDate = add(new Date(), 0, 0, 0, 0, 0, 0, 0, milliseconds);
	}

	/**
	 * adds the given offset to the given date and returns the new date. If the
	 * offset is positive, the returned date is in future. If the offset is
	 * negative, the returned date is in the past.
	 * 
	 * @param date
	 * @param years
	 * @param months
	 * @param weeks
	 * @param days
	 * @param hours
	 * @param minutes
	 * @param seconds
	 * @param milliseconds
	 * @return
	 */
	protected static Date add(Date date, int years, int months, int weeks,
			int days, int hours, int minutes, int seconds, int milliseconds) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.YEAR, years);
		cal.add(Calendar.MONTH, months);
		cal.add(Calendar.WEEK_OF_YEAR, weeks);
		cal.add(Calendar.DAY_OF_MONTH, days);
		cal.add(Calendar.HOUR_OF_DAY, hours);
		cal.add(Calendar.MINUTE, minutes);
		cal.add(Calendar.SECOND, seconds);
		cal.add(Calendar.MILLISECOND, milliseconds);
		return cal.getTime();
	}
}